<script setup>
import { ref, watch } from 'vue'
import { onLaunch, onShow, onLoad } from '@dcloudio/uni-app'
//引入API
import { getHotAPI } from '@/api/hot.js'
//引入子组件
import ItemVue from './Item.vue'
//配置ID匹配规则
const hotMap = [
  { type: '5', title: '特惠推荐', url: 'preference' },
  { type: '6', title: '爆款推荐', url: 'inVogue' },
  { type: '7', title: '一站买全', url: 'oneStop' },
  { type: '8', title: '新鲜好物', url: 'new' },
]
//创建数据
const category = ref()
const bannerPicture = ref()
const subTypes = ref([])
const currentIndex = ref(0) // 当前选中的下标
const goodList = ref([])
const page = ref(1)
const finished = ref(false)
// 请求数据初始化页面
const getHotObjData = async (category, data) => {
  const res = await getHotAPI(category, data)
  bannerPicture.value = res.result.bannerPicture
  subTypes.value = res.result.subTypes
  goodList.value.push(...subTypes.value[currentIndex.value].goodsItems.items)
  if (res.result.subTypes[currentIndex.value].goodsItems.pages === page.value) {
    finished.value = true
  }
}
onLoad(async (options) => {
  const id = options.type
  category.value = hotMap.find((item) => item.type === id)
  //设置标题
  uni.setNavigationBarTitle({
    title: category.value.title,
  })
  await getHotObjData(category.value.url, { page: 1, pageSize: 10 })

})
watch(currentIndex, async (newValue, oldValue) => {
  page.value = 1
  finished.value = false
  goodList.value = []
  await getHotObjData(category.value.url, { page: page.value, pageSize: 10 })
})
const onScrolltolower = async () => {
  if (finished.value) {
    uni.showToast({
      title: '没有更多了',
      icon: 'none',
    })
    return
  }
  page.value++
  await getHotObjData(category.value.url, { page: page.value, pageSize: 10 })
}
</script>

<template>
  <view>
    <view>
      <image :src="bannerPicture" style="width: 100%" />
    </view>
    <view class="tab">
      <view
        v-for="(item, index) in subTypes"
        :key="index"
        @tap="currentIndex = index"
        :class="{ active: currentIndex === index }"
      >
        {{ item.title }}
        {{ item.id }}
      </view>
    </view>

    <scroll-view
      scroll-y
      @scrolltolower="onScrolltolower"
      style="height: 900rpx"
    >
      <view class="item-row">
        <ItemVue
          v-for="(good, index) in goodList"
          :item="good"
          :key="index"
          :style="{ width: '50%' }"
        />
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
.tab {
  display: flex;
  justify-content: center;
  > view {
    padding: 10rpx;
    margin: 0 10rpx;

    &.active {
      color: #27ba9b;
      border-bottom: 2px solid #27ba9b;
    }
  }
}
.item-row {
  display: flex;
  flex-wrap: wrap;
}
</style>
